package com.pet.platform.controller;

import com.pet.platform.common.Result;
import com.pet.platform.exception.BusinessException;
import com.pet.platform.util.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/api/files")
public class FileController {
    
    private static final Logger logger = LoggerFactory.getLogger(FileController.class);
    
    @Autowired
    private FileUtil fileUtil;
    
    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Result<String> upload(@RequestParam("file") MultipartFile file,
                               @RequestParam(value = "directory", defaultValue = "common") String directory) {
        logger.info("文件上传请求开始处理 - 文件名: {}, 大小: {}, 目录: {}", 
                file.getOriginalFilename(), file.getSize(), directory);
        
        if (file.isEmpty()) {
            logger.error("上传失败: 文件为空");
            return Result.error("上传失败: 文件为空");
        }
        
        try {
            String filePath = fileUtil.uploadFile(file, directory);
            logger.info("文件上传成功 - 路径: {}", filePath);
            return Result.success(filePath);
        } catch (BusinessException e) {
            logger.error("文件上传业务异常: {}", e.getMessage());
            return Result.error(e.getMessage());
        } catch (Exception e) {
            logger.error("文件上传发生未知异常", e);
            return Result.error("文件上传失败: " + e.getMessage());
        }
    }
} 